﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.Enums.PregnancyTest;
using S.Common.helper;
using S.PregnancyTest.API.Application.Command;
using S.PregnancyTest.API.Dto;
using S.PregnancyTest.Domain;
using S.PregnancyTest.Domain.Model;
using S.PregnancyTest.Infrastructure.Interface;

namespace S.PregnancyTest.API.Application.CommandHandlers
{
    public class PregnancyTestUpdateHandler : IRequestHandler<PregnancyTestUpdateCommand, bool>
    {

        private readonly IPregnancyTestRepository repository;

        private readonly IMapper mapper;

        private readonly MyDbContext dbContext;

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public PregnancyTestUpdateHandler(IPregnancyTestRepository repository, IMapper mapper, MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.dbContext = dbContext;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }


        /// <summary>
        /// 修改种母妊检具体实现
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(PregnancyTestUpdateCommand request, CancellationToken cancellationToken)
        {
            //使用事物
            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    //获取到apollo上的网关地址
                    string Gateway = configuration.GetValue<string>("Gateway");


                    #region 修改妊检记录

                    PregnancyTestModel pregnancy = mapper.Map<PregnancyTestModel>(request);
                    pregnancy.UpdateDate = DateTime.Now;  //将修改时间设置为当前时间

                    await repository.UpdateAsync(pregnancy);

                    #endregion

                    #region 反填并修改种母历史记录

                    EditBreed editBreed = new EditBreed();

                    editBreed.EarTag = pregnancy.EarTag;

                    //反填种母历史记录
                    var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                    //将获取到的种母历史记录序列化
                    var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                    //判断是否获取到种母历史记录信息
                    if (string.IsNullOrWhiteSpace(jsonString))
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    //修改种母历史记录
                    response.PregnancyDate = pregnancy.PregnancyDate; //修改妊检日期
                    response.PregnancytestResult = Convert.ToInt32(pregnancy.PregnancytestResult); //修改妊检结果
                    response.IsEditor = pregnancy.PregnancytestResult == PregnancytestResultEnum.怀孕 ? true : false;//根据种母的妊检状态来更改是否可编辑的状态
                    response.UpdateBy = pregnancy.CreateBy;
                    //修改种母历史记录
                    var breeding = HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                    if (breeding == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion

                    #region 修改档案信息

                    //获取到妊检结果
                    var result = pregnancy.PregnancytestResult;
                    var UState = 0;

                    //根据妊检结果改变不同的繁殖状态
                    switch (result)
                    {
                        case (PregnancytestResultEnum)1:
                            UState = 5;
                            break;
                        case (PregnancytestResultEnum)2:
                            UState = 2;
                            break;
                        case (PregnancytestResultEnum)3:
                            UState = 4;
                            break;
                        case (PregnancytestResultEnum)4:
                            UState = 7;
                            break;
                        case (PregnancytestResultEnum)5:
                            UState = 3;
                            break;
                    }

                    var archives = EditReproductivePresenceState.UpdateReproductivePresenceState(pregnancy.EarTag, 1, UState, pregnancy.PregnancyDate, Gateway);
                    if (archives == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }
                    #endregion


                    //事物执行
                    tran.Commit();

                    return true;
                }
                catch (Exception)
                {
                    //事物回滚
                    tran.Rollback();

                    return false;
                }
            }
        }


        public class EditBreed
        {
            /// <summary>
            /// 可视耳号
            /// </summary>
            public string? EarTag { get; set; }
        }


        /// <summary>
        /// 羊只转舍
        /// </summary>
        public class SheepRescission
        {
            /// <summary>
            /// 转舍主键，自增标识列
            /// </summary>
            public int SheepRescissionId { get; set; }
            /// <summary>
            /// 可视耳标
            /// </summary>
            public string? EarTag { get; set; }
            /// <summary>
            /// 转舍日期
            /// </summary>
            public DateTime? SurrenderDate { get; set; }
            /// <summary>
            /// 转舍类型
            /// </summary>
            public int RoundType { get; set; }
            /// <summary>
            /// 转出栋舍
            /// </summary>
            public int TurnOutBuild { get; set; }
            /// <summary>
            /// 转出栏位
            /// </summary>
            public int TurnOutHuts { get; set; }
            /// <summary>
            /// 转出栋舍主键
            /// </summary>
            public int TurnOuBuildingManagementId { get; set; }
            /// <summary>
            /// 转出栏位主键
            /// </summary>
            public int TurnOuColumnManagementId { get; set; }
            /// <summary>
            /// 转入栋舍
            /// </summary>
            public int ShiftToBuild { get; set; }
            /// <summary>
            /// 转入栏位
            /// </summary>
            public int ShiftToHuts { get; set; }
            /// <summary>
            /// 转入栋舍主键
            /// </summary>
            public int ShiftToBuildingManagementId { get; set; }
            /// <summary>
            /// 转入栏位主键
            /// </summary>
            public int ShiftToColumnManagementId { get; set; }
            /// <summary>
            /// /// <summary>
            /// 品种
            /// </summary>
            public int? Variety { get; set; }
            /// 创建人
            /// </summary>
            public string? CreateBy { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? CreateDate { get; set; }
            /// <summary>
            /// 修改人
            /// </summary>
            public string? UpdateBy { get; set; }
            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime? UpdateDate { get; set; }
            /// <summary>
            /// 是否删除
            /// </summary>
            public bool IsDel { get; set; }
            /// <summary>
            /// 单据号
            /// </summary>
            public long DocumentNumbe { get; set; }
            /// <summary>
            /// 羊只类型
            /// </summary>
            public string? Type { get; set; }
            /// <summary>
            /// 性别
            /// </summary>
            public int Sex { get; set; }

        }


    }
}
